(() => {
  class Settings {
    constructor($exception) {
      this.exception = $exception;
    }
    post (settings) {
      return new Promise((resolve, reject) => {
        chrome.storage.local.get('settings', (result) => {
          if (result && Object.keys(result).length) {
            reject({
              status: 409,
              statusText: '设置已存在' 
            });
          }
          else if (!settings || !Object.keys(settings).length) {
            reject({
              status: 406,
              statusText: '设置不能为空'
            });
          }
          else {
            if (!settings.created) {
              settings.created = Date.now();
            }
            settings.modified = Date.now();
            chrome.storage.local.set({'settings': settings}, () => {
              resolve({
                status: 200,
                statusText: '设置已保存'
              })
            })
          }
        })
      });
    }
    delete () {
      return new Promise((resolve, reject) => {
        chrome.storage.local.get('settings', (result) => {
          if (result && Object.keys(result).length) {
            resolve({
              status: 204,
              statusText: '设置不存在' 
            });
          }
          else {
            chrome.storage.local.remove('settings', () => {
              resolve({
                status: 200,
                statusText: '设置已删除'
              })
            })
          }
        })
      });
    }
    put (settings) {
      return new Promise((resolve, reject) => {
        if (!settings || !Object.keys(settings).length) {
          reject({
            status: 406,
            statusText: '设置不能为空'
          });
        }
        else {
          if (!settings.created) {
            settings.created = Date.now();
          }
          settings.modified = Date.now();
          chrome.storage.local.set({'settings': settings}, (result) => {
            resolve({
              status: 200,
              statusText: '设置已保存'
            })
          })
        }
      });
    }
    get () {
      return new Promise((resolve, reject) => {
        chrome.storage.local.get('settings', (result) => {
          if (result && Object.keys(angular.copy(result)).length) {
            resolve({
              status: 200,
              statusText: 'OK',
              response: result.settings
            });
          }
          else {
            reject({
              status: 404,
              statusText: '设置不存在',
              response: null
            });
          }
        });
      });
    }
  }
  angular.module('app').factory('$settings', ['$exception', ($exception) => new Settings($exception)]);
})()